package com.newegg.whois.search;

import org.apache.commons.net.whois.WhoisClient;
import com.alibaba.fastjson.JSON;
import com.newegg.whois.model.DomainInfo;
import com.newegg.whois.util.DomainUtil;
import com.newegg.whois.util.WhoisParse;
import de.malkusch.whoisServerList.api.v1.DomainListFactory;
import de.malkusch.whoisServerList.api.v1.model.DomainList;
import java.io.IOException;
import java.io.Serializable;
import java.net.SocketException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WhoisUtil implements Serializable{
	private static final long serialVersionUID = -1068477756615779151L;

	static DomainList doaminList = new DomainListFactory().build();
	
	public static Map<String, Object> query(DomainInfo info) throws SocketException, IOException{
		Map<String, Object> result = new HashMap<>();
		List<String> whoisServer = info.getWhoisServers();
		while (whoisServer.size() > 0) {
			String server = whoisServer.get(0);
			whoisServer.remove(0);
			try {
				Map<String, Object> data = _query(info.getDomainName(), server);
				data = FieldFixPlugin.fix(info, data);
				if(data.containsKey("registrarWhoisServer")){
					String registrarWhoisServer = data.get("registrarWhoisServer").toString();
					if(!server.toLowerCase().equals(registrarWhoisServer.toLowerCase())){
						whoisServer.add(registrarWhoisServer);
					}
				}
				result.putAll(data);
			} catch (Exception e) {
				if(!result.containsKey("creationDate")){
					throw e;
				}
			}
		}
		return result;
	}
	
	static HashMap<String, Object> _query(String domain, String doaminServer)throws SocketException, IOException{
    	if(doaminServer == null){ throw new RuntimeException("can not find domain server"); }
    	WhoisClient whoisClient = new WhoisClient();
    	whoisClient.connect(doaminServer);
    	try {
    		whoisClient.setDefaultTimeout(3000);
    		String data = whoisClient.query(domain);
    		return WhoisParse.parse(data);
		} finally {
			whoisClient.disconnect();
		}
    }
	
	public static void main(String[] args) throws SocketException, IOException {
		System.setProperty("socksProxySet", "true");  
        System.setProperty("socksProxyHost", "10.16.238.79");
		System.setProperty("socksProxyPort", "8085");
		DomainInfo info = DomainUtil.getDomainInfo("apis.abs.org");
		Map<String, Object> data = query(info);
		System.out.println(JSON.toJSONString(data));
	}
}
